package com.fengxing.ams.web.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.fengxing.ams.web.facade.mouble.enrollment.MajorEnrollmentVO;
import com.fengxing.ams.web.facade.mouble.plan.PlanCacheVO;
import com.fengxing.ams.web.facade.mouble.student.StudentVO;

public class SerializeUtil {
	
	private static final ThreadLocal<Kryo> kryos = new ThreadLocal<Kryo>() {
	    protected Kryo initialValue() {
	        Kryo kryo = new Kryo();
	        kryo.register(MajorEnrollmentVO.class);
	        kryo.register(StudentVO.class);
	        kryo.register(PlanCacheVO.class);
	        // configure kryo instance, customize settings
	        kryo.setAutoReset(true);
	        return kryo;
	    };
	};
	
	public static byte[] serialize(Object object) {
		
		Output output = null;
		Kryo kryo = kryos.get();
	    try {
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        output = new Output(baos);
	        kryo.writeClassAndObject(output, object);
	        output.flush();
	        return baos.toByteArray();
	    }finally{
	        if(output != null)
	            output.close();
	    }
		
//		ObjectOutputStream oos = null;
//		ByteArrayOutputStream baos = null;
//		try {
//			// 序列化
//			baos = new ByteArrayOutputStream();
//			oos = new ObjectOutputStream(baos);
//			oos.writeObject(object);
//			byte[] bytes = baos.toByteArray();
//			return bytes;
//		} catch (Exception e) {
//
//		}
//		return null;
	}

	public static Object unserialize(byte[] bytes) {
		if(bytes == null || bytes.length == 0)
	        return null;
		Kryo kryo = kryos.get();
	    Input ois = null;
	    try {
	        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
	        ois = new Input(bais);
	        return kryo.readClassAndObject(ois);
	    } finally {
	        if(ois != null)
	            ois.close();
	    }
	}
}